/**
 * 设备统计表管理初始化
 */
var DeviceTotal = {
    id: "DeviceTotalTable",	//表格id
    seItem: null,		//选中的条目
    table: null,
    layerIndex: -1
};

/**
 * 初始化表格的列
 */
DeviceTotal.initColumn = function () {
    return [
        {field: 'selectItem', radio: true},
        {title: 'ID', field: 'id', visible: true, align: 'center', valign: 'middle'},
        {title: '设备id', field: 'deviceid', visible: true, align: 'center', valign: 'middle', sortable: true},
        {title: '指令', field: 'action', visible: true, align: 'center', valign: 'middle', sortable: true},
        {title: '日期', field: 'date', visible: true, align: 'center', valign: 'middle', sortable: true},
        {title: '个数', field: 'counts', visible: true, align: 'center', valign: 'middle', sortable: true}

    ];
};

/**
 * 检查是否选中
 */
DeviceTotal.check = function () {
    var selected = $('#' + this.id).bootstrapTable('getSelections');
    if (selected.length == 0) {
        Feng.info("请先选中表格中的某一记录！");
        return false;
    } else {
        DeviceTotal.seItem = selected[0];
        return true;
    }
};

/**
 * 点击添加设备统计表
 */
DeviceTotal.openAddDeviceTotal = function () {
    var index = layer.open({
        type: 2,
        title: '添加设备统计表',
        area: ['800px', '420px'], //宽高
        fix: false, //不固定
        maxmin: true,
        content: Feng.ctxPath + '/deviceTotal/deviceTotal_add'
    });
    this.layerIndex = index;
};

/**
 * 打开查看设备统计表详情
 */
DeviceTotal.openDeviceTotalDetail = function () {
    if (this.check()) {
        var index = layer.open({
            type: 2,
            title: '设备统计表详情',
            area: ['800px', '420px'], //宽高
            fix: false, //不固定
            maxmin: true,
            content: Feng.ctxPath + '/deviceTotal/deviceTotal_update/' + DeviceTotal.seItem.id
        });
        this.layerIndex = index;
    }
};

/**
 * 删除设备统计表
 */
DeviceTotal.delete = function () {
    if (this.check()) {
        var ajax = new $ax(Feng.ctxPath + "/deviceTotal/delete", function (data) {
            Feng.success("删除成功!");
            DeviceTotal.table.refresh();
        }, function (data) {
            Feng.error("删除失败!" + data.responseJSON.message + "!");
        });
        ajax.set("deviceTotalId", this.seItem.id);
        ajax.start();
    }
};

/**
 * 查询设备统计表列表
 */
DeviceTotal.search = function () {
    var queryData = {};
    queryData['deviceid'] = $("#deviceid").val();
    queryData['action'] = $("#action").val();
    queryData['startDate'] = $("#startDate").val();
    queryData['endDate'] = $("#endDate").val();
    DeviceTotal.table.refresh({query: queryData});
};

DeviceTotal.export = function () {
    var queryData = {};
    queryData['deviceid'] = $("#deviceid").val();
    queryData['action'] = $("#action").val();
    queryData['startDate'] = $("#startDate").val();
    queryData['endDate'] = $("#endDate").val();
    data=$('#' + this.id).bootstrapTable('getData')
    JSONToCSVConvertor(data,["设备id","指令","日期","个数"],["deviceid","action","date","counts"])
    console(table)
    //DeviceTotal.table.refresh({query: queryData});

};

function JSONToCSVConvertor(JSONData, ReportTitle,cols,ShowLabel) {
    //If JSONData is not an object then JSON.parse will parse the JSON string in an Object
    var arrData = typeof JSONData != 'object' ? JSON.parse(JSONData) : JSONData;

    var CSV = '';
    //Set Report title in first row or line
    title=""
    for (var index in ReportTitle){
        title+='"' + ReportTitle[index] + '",';
    }

    CSV += title + '\r\n';

    //This condition will generate the Label/Header
    if (ShowLabel) {
        var row = "";

        //This loop will extract the label from 1st index of on array
        for (var index in arrData[0]) {

            //Now convert each value to string and comma-seprated
            row += index + ',';
        }

        row = row.slice(0, -1);

        //append Label row with line break
        CSV += row + '\r\n';
    }

    //1st loop is to extract each row
    for (var i = 0; i < arrData.length; i++) {
        var row = "";

        //2nd loop will extract each column and convert it in string comma-seprated
        for (var index in cols) {
            var col = cols[index];
            if(arrData[i][col] == undefined){
                arrData[i][col]=''
            }
            row += '"' + arrData[i][col] + '",';
        }

        row.slice(0, row.length - 1);

        //add a line break after each row
        CSV += row + '\r\n';
    }

    if (CSV == '') {
        alert("Invalid data");
        return;
    }
    //
    // //Generate a file name
    // var fileName = "MyReport_";
    // //this will remove the blank-spaces from the title and replace it with an underscore
    // fileName += ReportTitle.replace(/ /g,"_");
    //
    // //Initialize file format you want csv or xls
    // var uri = 'data:text/csv;charset=utf-8,' + escape(CSV);
    //
    // // Now the little tricky part.
    // // you can use either>> window.open(uri);
    // // but this will not work in some browsers
    // // or you will not get the correct file extension
    //
    // //this trick will generate a temp <a /> tag
    // var link = document.createElement("a");
    // link.href = uri;
    //
    // //set the visibility hidden so it will not effect on your web-layout
    // link.style = "visibility:hidden";
    // link.download = fileName + ".csv";
    //
    // //this part will append the anchor tag and remove it after automatic click
    // document.body.appendChild(link);
    // link.click();
    // document.body.removeChild(link);


    //this trick will generate a temp "a" tag
    var link = document.createElement("a");
    link.id="lnkDwnldLnk";

    //this part will append the anchor tag and remove it after automatic click
    document.body.appendChild(link);

    var csv = CSV;
    blob = new Blob([csv], { type: 'text/csv' });
    var csvUrl = window.webkitURL.createObjectURL(blob);
    var filename = 'DeviceTotalTable.csv';
    $("#lnkDwnldLnk")
        .attr({
            'download': filename,
            'href': csvUrl
        });

    $('#lnkDwnldLnk')[0].click();
    document.body.removeChild(link);
}

$(function () {
    var defaultColunms = DeviceTotal.initColumn();
    var table = new BSTable(DeviceTotal.id, "/deviceTotal/list", defaultColunms);
    table.setPaginationType("client");
    DeviceTotal.table = table.init();
});
